package org.vacoor.nothing.ui.hotkey.impl.win;

import com.melloware.jintellitype.HotkeyListener;
import com.melloware.jintellitype.JIntellitype;
import org.vacoor.nothing.ui.hotkey.EmptyOSHotKeyBinder;
import org.vacoor.nothing.ui.hotkey.OSHotKeyEvent;
import org.vacoor.nothing.ui.hotkey.OSHotKeyListener;

import javax.swing.*;

/**
 * User: Vacoor
 */
class JIntellitypeKeyBinder extends EmptyOSHotKeyBinder implements HotkeyListener {
    private JIntellitype jIntellitype;

    public JIntellitypeKeyBinder(JIntellitype jIntellitype, int identifier) {
        super(identifier);
        this.jIntellitype = jIntellitype;
    }

    /**
     * 我去, JIntellitype 当热键冲突也不会抛出异常
     *
     * @param modifiers
     * @param key
     */
    @Override
    public boolean doRegisterHotKey(int modifiers, int key) {
        try {
            jIntellitype.removeHotKeyListener(this);
            jIntellitype.unregisterHotKey(getIdentifier());
            jIntellitype.registerSwingHotKey(getIdentifier(), modifiers, key);
            jIntellitype.addHotKeyListener(this);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * JIntellitype 回调
     *
     * @param i
     */
    @Override
    public void onHotKey(int i) {
        if (getIdentifier() == i) {
            final OSHotKeyEvent event = new OSHotKeyEvent(getIdentifier(), getModifiers(), getKey());
            for (final OSHotKeyListener l : getOSHotKeyListeners()) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        l.onOSHotKey(event);
                    }
                });
            }
        }
    }
}
